<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "admin_log".
 *
 * @property string $id
 * @property string $admin_id
 * @property string $catalog
 * @property string $url
 * @property string $intro
 * @property string $ip
 * @property integer $created_at
 */
class AdminLog extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'admin_log';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['catalog', 'url', 'ip', 'created_at'], 'required'],
            [['admin_id', 'created_at'], 'integer'],
            [['intro'], 'string'],
            [['catalog'], 'string', 'max' => 10],
            [['url'], 'string', 'max' => 255],
            [['ip'], 'string', 'max' => 15],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'admin_id' => '管理员ID',
            'catalog' => '日志类别',
            'url' => '日志URL地址',
            'intro' => '日志说明',
            'ip' => '访问IP地址',
            'created_at' => '创建时间',
        ];
    }

    /**
     * @inheritdoc
     * @return \app\models\query\AdminLogQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new \app\models\query\AdminLogQuery(get_called_class());
    }

    /**
     * 记录管理员操作日志
     * @param string $intro 操作内容
     * @param string $catalog 分类：'login','create','update','delete','other','browse'
     */
    public static function log($intro, $catalog = 'browse')
    {
        $_adminId = Yii::$app->user->id;
        if ($_adminId || $catalog == 'login') {
            $model = new AdminLog();
            $model->admin_id = $_adminId ? $_adminId : 0;
            $model->catalog = $catalog;
            $model->url = Yii::$app->request->getHostInfo() . Yii::$app->request->url;
            $model->intro = $intro;
            $model->ip = Yii::$app->request->userIP;
            $model->created_at = time();
            $model->save();
        }
    }

    public function getAdmin()
    {
        return $this->hasOne(Admin::className(), ['id' => 'admin_id']);
    }
}
